package com.itheima.controller;

/*
 *预约处理
 * */

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    //体检预约
    @RequestMapping("/addOrder")
    public Result addOrder(@RequestBody Map map) {
        //将从redis中取出的验证码与用户输入的验证码进行对比
        String telephone = (String) map.get("telephone");//map集合中获取手机号
        String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);//获取redis里存储的验证码
        String validateCode = (String) map.get("validateCode");//获取用户输入的验证码
        if (redisCode != null && redisCode.length() > 0 && validateCode != null && validateCode.length() > 0 && validateCode.equals(redisCode)) {
            //比对正确，继续完成业务
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置预约类型
            Result result = null;
            try {
                result = orderService.addOrder(map);
            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }
            if (result.isFlag()) {
                //预约成功，发送短信
                String orderDate = (String) map.get("orderDate");
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        } else {
            //比对错误，将错误信息返回
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }


    //根据id获取相关预约信息
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        Map map =null;
        try {
            map = orderService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
        return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
    }
}
